﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.IO;

namespace LaughingDog.Managers
{
    public sealed class AssetManager
    {
        #region Private Members

        private Dictionary<String, Texture2D> mTextureCache = new Dictionary<String, Texture2D>();

        #endregion

        #region Singleton

        static readonly AssetManager instance = new AssetManager();        

        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static AssetManager()
        {
        }

        AssetManager()
        {            
        }

        /// <summary>
        /// Returns the global instance of the AssetManager.
        /// </summary>
        public static AssetManager Instance
        {
            get
            {
                return instance;
            }
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Loads an asset.
        /// </summary>
        /// <typeparam name="T">The type of content.</typeparam>
        /// <param name="assetName">Path to the asset relative to the Content directory.</param>
        /// <returns>The loaded asset.</returns>
        public T Load<T>(String assetName)
        {
            return Engine.Game.Content.Load<T>(assetName);
        }

        /// <summary>
        /// Loads a Texture2D into the manager.
        /// </summary>
        /// <param name="assetName">Path to the asset relative to the Content directory.</param>
        /// <returns>The loaded Texture2D.</returns>
        public Texture2D LoadTexture2D(String assetName)
        {
            Texture2D texture;

            if (mTextureCache.ContainsKey(assetName))
                return mTextureCache[assetName];

            if (Path.HasExtension(assetName) && File.Exists(assetName))
                texture =  Texture2D.FromFile(Engine.Game.GraphicsDevice, assetName);
            else
                texture = Engine.Game.Content.Load<Texture2D>(assetName);

            mTextureCache.Add(assetName, texture);

            return texture;
        }

        #endregion
    }
}
